package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 菜品管理
 */
@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {
    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategoryService categoryService;

    /**
     * 新增菜品
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto) {
        log.info("接收到的 DishDto :" + dishDto);
        // 保存菜品数据
        boolean saveDishFlag = dishService.save(dishDto);
        if (!saveDishFlag) {
            return R.error("菜品表保存失败");
        }
        List<DishFlavor> flavors = dishDto.getFlavors();
        if (flavors != null && flavors.size() >= 1) {
            for (DishFlavor flavor : flavors) {
                // 为菜品口味表 设置 对应的菜品id
                flavor.setDishId(dishDto.getId());
                boolean saveDishFlavorFlag = dishFlavorService.save(flavor);
                if (!saveDishFlavorFlag) {
                    return R.error("菜品口味表保存失败");
                }
            }
        }
        return R.success("添加菜品成功");
    }

    /**
     * 菜品信息分页查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public /*R<Page<DishDto>>*/ R<Map<String, Object>> page(Integer page, Integer pageSize, String name) {
        Page<Dish> dishPage = new Page<>(page, pageSize);
        // new 一个用于返回的 map 集合
        Map<String, Object> map = new HashMap<>();
        // Page<DishDto> dishDtoPage = new Page<>();
        LambdaQueryWrapper<Dish> dishLQW = new LambdaQueryWrapper<>();
        //添加过滤条件
        dishLQW.like(name != null, Dish::getName, name);
        //执行分页查询
        dishService.page(dishPage, dishLQW);
        //拷贝除 "records" 以外的其他属性 主要是 total
        // BeanUtils.copyProperties(dishPage, dishDtoPage, "records");
        // 将前台需要的 total 数据放入 map
        map.put("total", dishPage.getTotal());
        List<DishDto> dishDtos = new ArrayList<>();
        for (Dish dish : dishPage.getRecords()) {
            DishDto dishDto = new DishDto();
            // 属性拷贝 dish --> dishDto
            BeanUtils.copyProperties(dish, dishDto);
            Long categoryId = dish.getCategoryId(); //分类Id
            //根据id查询分类对象
            Category categoryById = categoryService.getById(categoryId);
            if (categoryById != null) {
                dishDto.setCategoryName(categoryById.getName()); //分类名称
            }
            dishDtos.add(dishDto);
        }
        // 将前台需要的 records 数据放入 map
        map.put("records", dishDtos);
        // dishDtoPage.setRecords(dishDtos);
        //return R.success(dishDtoPage);
        return R.success(map);
    }

    /**
     * 根据id查询菜品信息和对应的口味信息
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> queryDishById(@PathVariable Long id) {
        Dish dishById = dishService.getById(id);
        DishDto dishDto = new DishDto();
        BeanUtils.copyProperties(dishById, dishDto, "flavors");
        LambdaQueryWrapper<DishFlavor> dishFlavorLQW = new LambdaQueryWrapper<>();
        dishFlavorLQW.eq(DishFlavor::getDishId, dishById.getId());
        List<DishFlavor> list = dishFlavorService.list(dishFlavorLQW);
        dishDto.setFlavors(list);
        return R.success(dishDto);
    }

    /**
     * 修改菜品
     */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto) {
        log.info(dishDto.toString());
        dishService.updateById(dishDto);
        List<DishFlavor> flavors = dishDto.getFlavors();
        /*
         * 修改口味比较麻烦, 因为这儿的修改实际包括 新增 删除 修改 口味
         * 因此采用迂回方式 删除原先与菜品关联的所有口味 增加修改框中所有的口味 而不是真正的修改,
         * */
//        if (flavors != null && flavors.size() >= 1) {
//            for (DishFlavor flavor : flavors) {
//                DishFlavor byId = dishFlavorService.getById(flavor);
//            }
//        }
        LambdaQueryWrapper<DishFlavor> dishFlavorLQW = new LambdaQueryWrapper<>();
        dishFlavorLQW.eq(DishFlavor::getDishId, dishDto.getId());
        boolean removeFlavorFlag = dishFlavorService.remove(dishFlavorLQW);
        for (DishFlavor flavor : flavors) {
            // 为菜品口味表 设置 对应的菜品id
            flavor.setDishId(dishDto.getId());
            flavor.setId(null);
            boolean saveDishFlavorFlag = dishFlavorService.save(flavor);
            if (!saveDishFlavorFlag) {
                return R.error("菜品口味表保存失败");
            }
        }
        return R.success("修改菜品成功");
    }

    @PostMapping("/status/{status}")
    public R<String> changeStatus(@PathVariable Integer status, @RequestParam List<Long> ids) {
        log.info("ids : " + ids.toString());
        List<Dish> dishes = dishService.listByIds(ids);
        for (Dish dish : dishes) {
            dish.setStatus(status);
        }
        boolean updateBatchFlag = dishService.updateBatchById(dishes);
        if (!updateBatchFlag) {
            R.error("菜品状态修改失败");
        }
        return R.success("菜品状态修改成功");
    }

    @DeleteMapping
    public R<String> delete(@RequestParam List<Long> ids) {
        log.info("ids : " + ids.toString());
        boolean removeByIdsFlag = dishService.removeByIds(ids);
        if (!removeByIdsFlag) {
            R.error("菜品删除失败");
        }
        return R.success("菜品删除成功");
    }

    /**
     * 备用
     * 根据条件查询对应的菜品数据
     *
     * @param categoryId
     * @return
     */
    @GetMapping("/list1")
    public R<List<Dish>> listDishByCategoryId(@RequestParam Long categoryId) {
        log.info("categoryId : " + categoryId);
        if (categoryId == null) {
            return R.error("请求参数错误");
        }
        LambdaQueryWrapper<Dish> dishLQW = new LambdaQueryWrapper<>();
        dishLQW.eq(Dish::getCategoryId, categoryId);
        // 选择 启用 状态的菜品
        dishLQW.eq(Dish::getStatus, 1);
        List<Dish> list = dishService.list(dishLQW);
        return R.success(list);
    }

    /**
     * 备用
     *
     * @param dish
     * @return
     */
    @GetMapping("/list2")
    public R<List<Dish>> listByCondition(Dish dish) {
        log.info("dish:{}", dish);
        return R.success(null);
    }

    /**
     * 备用
     * 根据条件查询对应的菜品数据
     * (@RequestParam Long categoryId)
     *
     * @param categoryId
     * @return
     */
    @GetMapping("/list")
    public R<List<DishDto>> listDishDtoByCategoryId(@RequestParam Long categoryId, Integer status) {
        log.info("categoryId : " + categoryId);
        if (categoryId == null) {
            return R.error("请求参数错误");
        }
        LambdaQueryWrapper<Dish> dishLQW = new LambdaQueryWrapper<>();
        dishLQW.eq(Dish::getCategoryId, categoryId);
        // 选择 启用 状态的菜品
        dishLQW.eq(status != null, Dish::getStatus, status);
        List<Dish> list = dishService.list(dishLQW);
        List<DishDto> dishDtos = new ArrayList<>();
        for (Dish dish : list) {
            DishDto dishDto = new DishDto();
            // 把dish的属性值copy给dishDto
            BeanUtils.copyProperties(dish, dishDto);
            // 根据 dishId 查询菜品的口味数据
            LambdaUpdateWrapper<DishFlavor> dishFlavorLQW = new LambdaUpdateWrapper<>();
            dishFlavorLQW.eq(DishFlavor::getDishId, dish.getId());
            List<DishFlavor> flavors = dishFlavorService.list(dishFlavorLQW);
            dishDto.setFlavors(flavors);
            dishDtos.add(dishDto);
        }
        return R.success(dishDtos);
    }

}
